package com.xiao.wiki.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiao.wiki.domain.Ebook;
import com.xiao.wiki.domain.EbookExample;
import com.xiao.wiki.mapper.EbookMapper;
import com.xiao.wiki.req.EbookQueryReq;
import com.xiao.wiki.req.EbookSaveReq;
import com.xiao.wiki.resp.EbookQueryResp;
import com.xiao.wiki.resp.PageResp;
import com.xiao.wiki.util.CopyUtil;
import com.xiao.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ：降蓝
 * @description：TODO
 * @date ：2021/11/13 21:32
 */
@Service
public class EbookService {

    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getName()))
        {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if(!ObjectUtils.isEmpty(req.getCategoryId2()))
        {
            criteria.andCategory2IdEqualTo(  req.getCategoryId2() );
        }

        // 从数据库查询数据
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> ebookPageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}",ebookPageInfo.getTotal());
        LOG.info("总页数：{}",ebookPageInfo.getPages());


        PageResp<EbookQueryResp> pageResp = new PageResp();
        // 将数据转换为响应需要的字段
        List<EbookQueryResp> ebookResps = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        pageResp.setTotal(ebookPageInfo.getTotal());
        pageResp.setList(ebookResps);
        return pageResp;
    }

    /**
     * 保存
     */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //  新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            //  更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    /**
     * 删除
     */
    public void delete(Long id) {
            ebookMapper.deleteByPrimaryKey(id);
    }


}
